import Vue from 'vue'
import Router from 'vue-router'
import store from "@/store";

Vue.use(Router)

import { Message } from 'element-ui';

export const constantRoutes = [
    {
        path: '/login',
        name: "Login",
        component: () => import('@/views/login/index.vue')
    },
    {
        path: '/404',
        name: "404",
        component: () => import('@/views/404'),
    },
    {
        path: "/",
        name: "Home",
        redirect: '/home',
        component: () => import('@/layout/index.vue'),
        children: [
            // {path: "/shoppingManage/userManage",component: () => import("@/views/shoppingManage/userManage/index.vue")},
            {path:"/itemManage",name:"itemManage",component:()=>import('@/views/purchaseItemManage/itemManage'),meta: {title: "采购项目管理 / 项目管理"}},
            {path:"/approvalItemManage",name:"approvalItemManage",component:()=>import('@/views/supplierQualificationApproval/approvalItemManage'),meta: {title: "供应商资格条件审批 / 项目管理"}},
            //{path:"/potentialSuppliers",name:"potentialSuppliers",component:()=>import('@/views/potentialSuppliers/index')},
            {path:"/potentialSuppliersAdd",name:"potentialSuppliersAdd",component:()=>import('@/views/potentialSuppliers/add'),meta: {title: "潜在供应商 / 添加"}},
            //{path:"/archive",name:"archive",component:()=>import('@/views/archive/index')},
            {path:"/archiveManger",name:"archiveManger",component:()=>import('@/views/archive/archiveManger'),meta: {title: "一键归档 / 管理"}},
            //{path:"/acceptanceApproval",name:"acceptanceApproval",component:()=>import('@/views/acceptanceApproval/index')},
            {path:"/acceptanceApprovalManger",name:"acceptanceApprovalManger",component:()=>import('@/views/acceptanceApproval/acceptanceApprovalManger'),meta: {title: "验收审批 / 管理"}},
            //{path:"/archiveApproval",name:"archiveApproval",component:()=>import('@/views/archiveApproval/index')},
            {path:"/archiveApproveManger",name:"archiveApproveManger",component:()=>import('@/views/archiveApproval/archiveApproveManger')},
            {path:"/potentialSuppliersApprovalManager",name:"potentialSuppliersApprovalManager",component:()=>import('@/views/potentialSuppliersApproval/Manager.vue'),meta: {title: "潜在供应商审批 / 管理"}},
            // {
            // path: "/shoppingManage/userManage",
            // component: () => import("@/views/shoppingManage/userManage/index.vue")
            // },
            {
                path: "/ContractSupplierQuotationManage",
                component:()=>import("@/views/ContractSupplierQuotationManage/index"),
                meta: {title: "供应商报价/供应商报价管理"}
            },
            {
                path: "/DealSupplierApprovalManage",
                component:()=>import("@/views/DealSupplierApprovalManage/index"),
                meta: {title: "成交供应商审批/成交供应商审批管理"}
            },
            ,
            {
                path: "/AttendanceSheetManage",
                component:()=>import("@/views/AttendanceSheetManage/index"),
                meta: {title: "签到表/签到表管理"}
            // },
            // {
            //     path: "/ContractApprove",
            //     component:()=>import("@/views/contractApprove/index")
            }
        ]
    },
    {
        path: "/changePwd",
        name: "ChangePwd",
        component: () => import('@/views/User/LoginGoAlterPassword/index.vue')
    // },
    // {
    //     path: "condition",
    //     name: "Condition",
    //     component: () => import('@/views/condition/index.vue')
    },
    {
        path: "/ceshi",
        name: "测试",
        component: () => import('@/components/uploadFile/shardingUploadFile.vue')
    }
]


const createRouter = () => new Router({
    mode: 'history', // require service support
    scrollBehavior: () => ({y: 0}),
    routes: constantRoutes
})

const router = createRouter(
    {
    routes: [

    ]
}
)
//
//提供一个重置路由的方法
export const resetRouter = () => {
    router.matcher = createRouter()
}

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem("token")
    const tokenExpiration = localStorage.getItem("tokenExpiration")
    const now = new Date()

    console.log(to.path + "\t" + now.getTime())
    console.log(localStorage)

    // 如果路由要前往登录页
    if (to.path === "/login") {
        if ((token || now.getTime() < parseInt(tokenExpiration)) && now.getTime() < parseInt(tokenExpiration)) {
            next("/") // 如果已登录且 Token 未过期，则重定向到首页
        } else {
            next()
        }

    } else {
        // 如果路由不是前往登录页
        // 判断用户是否已登录，如果未登录、Token 过期或 Token 过期时间不存在，则重定向到登录页
        if ((!token || now.getTime() > parseInt(tokenExpiration)) && to.path !== "/changePwd") {
            localStorage.removeItem("token")
            localStorage.removeItem("tokenExpiration")
            localStorage.removeItem("menuList")
            localStorage.removeItem("userinfo")
            if(to.path !== "/home")
                Message.warning("请重新登录");
            next("/login")
        } else {
            next()
        }
    }

})


// 注意：刷新页面会导致页面路由重置
export const setRoutes = () => {
    const storeMenus = localStorage.getItem("menuList");
    if (storeMenus) {
        //获取当前的路由对象名称数组
        const currentRoutesNames = router.getRoutes().map(v => v.name)
        console.log(currentRoutesNames)
        if (!currentRoutesNames.includes("Manager")) {
            //动态拼装路由
            const manageMenus = {
                path: "/home",
                name: "Manager",
                component: () => import('@/layout/index.vue'),
                children: [],
                meta: {title: "首页"}
            }
            const menus = JSON.parse(storeMenus)
            menus.forEach(item => {
                if (item.children.length >= 0) {
                    item.children.forEach(item1 => {
                        if (item1.url) {
                            let itemMenus1 =
                                {
                                    path: item1.url,
                                    name: item1.url.replace("/", ""),
                                    component: () => import('../views' + item1.url + '/index.vue'),
                                    meta: {title: item1.moduleName}
                                }
                            manageMenus.children.push(itemMenus1)
                        }
                    })
                }

                // if(item.path){
                //     let itemMenus = {path:item.url.replace("/",""),name:item.moduleName,component:()=>import('../views/'+item.pagePath+'.vue')}
                //     manageMenus.children.push(itemMenus)
                // }else if(item.children.length){
                //     item.children.forEach(item1=>{
                //         if(item1.path){
                //             let itemMenus1 = {path:item1.path.replace("/",""),name:item1.moduleName,component:()=>import('../views/'+item1.pagePath+'.vue')}
                //             manageMenus.children.push(itemMenus1)
                //         }
                //     })
                // }
            })
            //动态添加到现在的路由对象
            router.addRoute(manageMenus)
        }
    }
}

//重置则再次set路由
setRoutes()


export default router

